import requestApi from '@/util/request';
import { type Device } from '@/types/device';

export async function getDeviceList(): Promise<Array<Device>> {
  try {
    const data = await requestApi(`/device/get_device_list`, 'get', {});
    const deviceList: Array<Device> = []
    for (let i = 0; i < data.length; i++) {
      const device: Device = {
        id: data[i].id,
        name: data[i].name,
        ip: data[i].ip,
        port: data[i].port,
        protocol: data[i].protocol,
        isConnected: data[i].is_connected,
      }
      deviceList.push(device);
    }
    return deviceList;
  } catch (error) {
    console.error('Error fetching device list:', error);
    return [];
  }
}

export async function addDevice(device: Device): Promise<boolean> {
  try {
    return await requestApi(`/device/add_device`, 'post', {
      "device_name": device.name,
      "ip": device.ip,
      "port": device.port,
      "protocol": device.protocol,
    });
  } catch (error) {
    return false;
  }
}

export async function editDevice(device: Device): Promise<boolean> {
  try {
    return await requestApi(`/device/edit_device`, 'post', {
      "device_id": device.id,
      "device_name": device.name,
      "ip": device.ip,
      "port": device.port,
      "protocol": device.protocol,
    });
  } catch (error) {
    return false;
  }
}

export async function deleteDevice(device_name: string): Promise<boolean> {
  try {
    return await requestApi(`/device/delete_device`, 'post', {
      "device_name": device_name,
    });
  } catch (error) {
    return false;
  }
}

export async function getLatestMessage(device_name: string): Promise<Array<string>> {
  try {
    return await requestApi(`/device/get_latest_message`, 'post', {
      "device_name": device_name,
    });
  } catch (error) {
    return [];
  }
}

// 打开连接 API 函数
export async function openConnection(deviceName: string): Promise<boolean> {
  try {
    return await requestApi(`/device/open_connection`, 'post', {
      "device_name": deviceName,
    });
  } catch (error) {
    console.error('Error opening connection:', error);
    return false;
  }
}

// 断开连接 API 函数
export async function closeConnection(deviceName: string): Promise<boolean> {
  try {
    return await requestApi(`/device/close_connection`, 'post', {
      "device_name": deviceName,
    });
  } catch (error) {
    console.error('Error closing connection:', error);
    return false;
  }
}